package com.xw.tools.view;

import com.xw.tools.util.GroovyUtil;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class CustomizeTextConvertWin extends AbstractWin {

    public void start() {
        Stage primaryStage = new Stage();
        primaryStage.setTitle("文本转换");
        Scene scene = new Scene(new VBox(), 800, 495);
        initView(scene, primaryStage);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void initView(Scene scene, Stage primaryStage) {
        TextArea inputTextArea = new TextArea();
        TextArea scriptTextArea = new TextArea();
        TextArea outputTextArea = new TextArea();
        inputTextArea.setFont(Font.font(16));
        outputTextArea.setFont(Font.font(16));
        Label label = new Label("groovy脚本");
        Button button = new Button("转换");
        button.setOnAction((ActionEvent t) -> {
            String inputText = inputTextArea.getText();
            String scriptText = scriptTextArea.getText();
            if (inputText == null || inputText.isEmpty()) {
                return;
            }
            if (scriptText == null || scriptText.isEmpty()) {
                outputTextArea.setText(inputText);
                return;
            }

            Map<String, Object> contextMap = new HashMap<>();
            contextMap.put("inputText", inputText);
            Object result = GroovyUtil.run(scriptText, contextMap);
            if (result == null) {
                outputTextArea.setText("");
            } else {
                outputTextArea.setText(Objects.toString(result, ""));
            }

        });

        VBox box = (VBox) scene.getRoot();
        VBox.setVgrow(inputTextArea, Priority.ALWAYS);
        box.getChildren().add(inputTextArea);
        box.getChildren().add(label);
        VBox.setVgrow(scriptTextArea, Priority.ALWAYS);
        box.getChildren().add(scriptTextArea);
        box.getChildren().add(button);
        VBox.setVgrow(outputTextArea, Priority.ALWAYS);
        box.getChildren().add(outputTextArea);
    }

    @Override
    public void show() {
        start();
    }
}
